<template>
  <div class="application-list">
    <el-card class="box-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" ref="searchForm">
          <el-form-item label="申请状态" prop="status">
            <el-select v-model="searchForm.status" placeholder="请选择申请状态" clearable>
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" v-loading="loading" border style="width: 100%">
        <el-table-column prop="applicationDate" label="申请时间" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.applicationDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="jobName" label="职位名称">
          <template slot-scope="scope">
            <el-tooltip effect="dark" :content="scope.row.jobInfo ? scope.row.jobInfo.remark : ''" placement="top">
              <span>{{ scope.row.jobInfo ? scope.row.jobInfo.jobName : '' }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="seekerName" label="求职者信息">
          <template slot-scope="scope">
            <el-button type="text" @click="handleViewSeeker(scope.row.seekerId)">
              {{ scope.row.seekerInfo ? scope.row.seekerInfo.name : '' }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="申请状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <template v-if="scope.row.status === 0">
              <el-button type="success" size="mini" @click="handleUpdate(scope.row.id, 1, scope.row.seekerId)">接收</el-button>
              <el-button type="danger" size="mini" @click="handleUpdate(scope.row.id, 2, scope.row.seekerId)">拒绝</el-button>
            </template>
            <template v-else>
              <span>{{ formatDateTime(scope.row.updateTime) }}</span>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>

      <!-- 求职者详情对话框 -->
      <el-dialog title="求职者详情" :visible.sync="seekerDialogVisible" width="500px">
        <div v-if="currentSeeker" class="seeker-info">
          <div class="info-item">
            <span class="label">姓名：</span>
            <span>{{ currentSeeker.name }}</span>
          </div>
          <div class="info-item">
            <span class="label">性别：</span>
            <span>{{ currentSeeker.gender === 'M' ? '男' : currentSeeker.gender === 'F' ? '女' : '' }}</span>
          </div>
          <div class="info-item">
            <span class="label">年龄：</span>
            <span>{{ currentSeeker.age }}</span>
          </div>
          <div class="info-item">
            <span class="label">联系电话：</span>
            <span>{{ currentSeeker.contactNumber }}</span>
          </div>
          <div class="info-item">
            <span class="label">就业状态：</span>
            <span>{{ currentSeeker.hiredStatus === 1 ? '已就业' : '未就业' }}</span>
          </div>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'ApplicationList',
  data() {
    return {
      loading: false,
      searchForm: {
        status: null
      },
      statusOptions: [
        { label: '全部', value: null },
        { label: '未处理', value: 0 },
        { label: '已聘用', value: 1 },
        { label: '已拒绝', value: 2 }
      ],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      seekerDialogVisible: false,
      currentSeeker: null
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 获取申请列表
    async fetchData() {
      this.loading = true
      try {
        const response = await this.$http.post('/job-application/page', {
          ...this.searchForm,
          employerId: this.$store.state.user.user.referenceId,
          current: this.currentPage,
          size: this.pageSize
        })
        if (response.data.code === 200) {
          // 获取申请列表数据
          const applications = response.data.data.records
          this.total = response.data.data.total

          // 获取职位和求职者信息
          const jobPromises = applications.map(app => 
            this.$http.get(`/job/${app.jobId}`).then(res => res.data.data)
          )
          const seekerPromises = applications.map(app => 
            this.$http.get(`/job-seeker/info/${app.seekerId}`).then(res => res.data.data)
          )

          // 等待所有请求完成
          const [jobs, seekers] = await Promise.all([
            Promise.all(jobPromises),
            Promise.all(seekerPromises)
          ])

          // 合并数据
          this.tableData = applications.map((app, index) => ({
            ...app,
            jobInfo: jobs[index],
            seekerInfo: seekers[index]
          }))
        } else {
          this.$message.error('获取申请列表失败')
        }
      } catch (error) {
        console.error('获取申请列表失败:', error)
        this.$message.error('获取申请列表失败')
      } finally {
        this.loading = false
      }
    },
    // 查看求职者详情
    async handleViewSeeker(seekerId) {
      try {
        const response = await this.$http.get(`/job-seeker/info/${seekerId}`)
        if (response.data.code === 200) {
          this.currentSeeker = response.data.data
          this.seekerDialogVisible = true
        }
      } catch (error) {
        console.error('获取求职者详情失败:', error)
        this.$message.error('获取求职者详情失败')
      }
    },
    // 处理申请状态更新
    async handleUpdate(id, status, seekerId) {
      const statusText = status === 1 ? '接收' : '拒绝'
      try {
        await this.$confirm(`确认要${statusText}该申请吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await this.$http.get('/job-application/update', {
          params: { 
            id,
            status,
            employerId: this.$store.state.user.user.referenceId,
            seekerId
          }
        })
        
        if (response.data.code === 200) {
          this.$message.success('操作成功')
          this.fetchData()
        } else {
          this.$message.error(response.data.message || '操作失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('处理申请失败:', error)
          this.$message.error('处理申请失败')
        }
      }
    },
    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    // 重置搜索
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.handleSearch()
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    // 格式化时间
    formatDateTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },
    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        0: 'info',
        1: 'success',
        2: 'danger'
      }
      return statusMap[status] || 'info'
    },
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '未处理',
        1: '已聘用',
        2: '已拒绝'
      }
      return statusMap[status] || '未知'
    }
  }
}
</script>

<style scoped>
.application-list {
  padding: 20px;
}
.search-bar {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
.seeker-info {
  padding: 20px;
}
.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}
.info-item .label {
  width: 100px;
  color: #606266;
  font-weight: bold;
}
</style> 